<template>
  <a-modal
      title="API权限"
      width="90%"
      style="min-width: 1000px"
      :maskClosable="false"
      :destroyOnClose="true"
      @cancel="closeModal"
      :visible="true">

    <!--搜索-->
    <a-form
        ref="defSearch"
        :model="defSearch.param"
        :rules="defSearch.rules"
        :labelCol="{style: {width: '60px'}}"
        class="fx shadow3">

      <!--搜索条件-->
      <div class="fx_row fx_wrap fx_start" style="width: calc(100%)">
        <a-form-item label="模块名称" name="module_name" style="width: 220px">
          <a-input allow-clear v-model:value="defSearch.param.module_name" placeholder="请输入模块名称"></a-input>
        </a-form-item>
        <a-form-item label="API名称" name="api_name" style="width: 220px">
          <a-input allow-clear v-model:value="defSearch.param.api_name" placeholder="请输入API名称"></a-input>
        </a-form-item>

        <a-form-item label="请求地址" name="path" style="width: 220px">
          <a-input allow-clear v-model:value="defSearch.param.path" placeholder="请输入请求地址"></a-input>
        </a-form-item>

        <a-form-item label="接口状态" name="use_state" style="width: 220px">
          <a-select v-model:value="defSearch.param.use_state" placeholder="请选择" :allowClear="true">
            <a-select-option v-for="(item,index) in option.useStatus" :value=item.value>
              {{
                item.label
              }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="请求方式" name="request_type" style="width: 220px">
          <a-select v-model:value="defSearch.param.request_type" placeholder="请选择" :allowClear="true">
            <a-select-option v-for="(item,index) in option.request_type" :value=item.value>
              {{
                item.label
              }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="登录校验" name="check_login" style="width: 220px">
          <a-select v-model:value="defSearch.param.check_login" placeholder="请选择" :allowClear="true">
            <a-select-option v-for="(item,index) in option.check_login" :value=item.value>
              {{
                item.label
              }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="权限校验" name="check_permission" style="width: 220px">
          <a-select v-model:value="defSearch.param.check_permission" placeholder="请选择" :allowClear="true">
            <a-select-option v-for="(item,index) in option.check_permission" :value=item.value>
              {{
                item.label
              }}
            </a-select-option>
          </a-select>
        </a-form-item>

      </div>

      <!--按钮-->
      <a-form-item class="search_button_2">
        <a-button type="primary" @click.stop="search" class="font12">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button style="margin-left: 10px" @click.stop="()=>{ resetForm('defSearch'); }" class="font12">
          <template #icon>
            <UndoOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>

    </a-form>

    <!--已勾选内容展示-->
    <div v-if="defTable.selectRow.length>0" style="border:2px solid #1890FF80;border-radius: 5px;padding: 8px"
         class="fx_row fx_wrap">
      <div style="font-size: 14px;font-weight: 700;color: #8c8a8a;margin: 3px">已勾选({{ defTable.selectRow.length }}):
      </div>
      <a-tag v-for="(item,index) in defTable.selectRow" closable @close.prevent="removeCheck(item,index)"
             style="margin: 3px">
        {{ item.path }}
      </a-tag>
    </div>

    <!--表格-->
    <div ref="tableDiv" :style="{background:'#FFFFFF',minHeight:option.tableMinHeight}">
      <a-table
          sticky
          ref="defTable"
          :row-key="record => record.id"
          style="height: 100%"
          :pagination="false"
          :size="defTable.size"
          :columns="defTable.column"
          :expandRowByClick="true"
          :data-source="defTable.data"
          :rowSelection="defTable.rowSelection()"
          @resizeColumn="(w, col) => {col.width = w;}">

        <!--表格内容-->
        <template #bodyCell="{ text, record, index, column  }">
          <!--目录-->
          <template v-if="column.dataIndex === 'api_name'">
            <!--          <a-tag>-->
            {{ text }}
            <!--          </a-tag>-->
          </template>

          <template v-if="column.dataIndex === 'path'">
            <!--          <a-tag>-->
            {{ text }}
            <!--          </a-tag>-->
          </template>

          <template v-if="column.dataIndex === 'status'">
            <a-tag v-if="text==0" color="green" class="round">启用</a-tag>
            <a-tag v-if="text==1" color="orange" class="round">停用</a-tag>
          </template>

          <!--访问间隔-->
          <template v-if="column.dataIndex === 'access_time'">
            <a-tag v-if="text==0" color="orange" class="round">无限制</a-tag>
            <template v-else>{{ text }}</template>
          </template>

          <!--        登录校验-check_login -->
          <template v-if="column.dataIndex === 'check_login'">
            <a-tag v-if="text==0" color="blue" class="round">已开启</a-tag>
            <a-tag v-if="text==1" color="orange" class="round">已关闭</a-tag>
          </template>
          <!--        权限校验-check_permission-->

          <template v-if="column.dataIndex === 'check_permission'">
            <a-tag v-if="text==0" color="blue" class="round">已开启</a-tag>
            <a-tag v-if="text==1" color="orange" class="round">已关闭</a-tag>
          </template>

          <!--        保存操作日志-log_open_action-->
          <template v-if="column.dataIndex === 'log_open_action'">
            <a-tag v-if="text==0" color="blue" class="round">已开启</a-tag>
            <a-tag v-if="text==1" color="orange" class="round">已关闭</a-tag>
          </template>
          <!--       <template v-if="column.dataIndex === 'check_re_submit'">-->
          <!--          <a-tag v-if="text==0" color="blue" class="round">已开启</a-tag>-->
          <!--          <a-tag v-if="text==1" color="orange" class="round">已关闭</a-tag>-->
          <!--        </template>-->

          <!--        请求类型-request_type-->
          <template v-if="column.dataIndex === 'request_type'">
            <a-tag>{{ text }}</a-tag>
          </template>

          <!--        接口状态-use_state-->
          <template v-if="column.dataIndex === 'use_state'">
            <a-tag v-if="text==0" color="blue">已启用</a-tag>
            <a-tag v-if="text==1" color="orange">已禁用</a-tag>
          </template>

          <!--操作-->
          <template v-if="column.dataIndex === 'action'">
            <!--详情-->
            <a @click.stop="openInfo(record)" class="table_action_a">详情</a>
          </template>

        </template>

      </a-table>
    </div>

    <!--分页-->
    <Pagination class="table_page"
                :current="defPage.current"
                :total="defPage.total"
                :page-size="defPage.size"
                @change="defPage.change"/>

    <!--详情Dialog-->
    <a-modal
        title="接口详情"
        style="min-width: 800px"
        :maskClosable="false"
        :destroyOnClose="true"
        v-model:visible="option.openInfo">

      <!--新增表单-->
      <a-form
          ref="defForm"
          label-align="right"
          :model="defForm.data"
          :rules="defForm.rules"


          class="go_shadow go_radius">

        <h3>基础信息</h3>
        <div style="margin-left: 30px">

          <a-form-item label="模块名称" name="module_name">
            <a-input readonly v-model:value="defForm.data.module_name" placeholder="请输入模块名称" :allowClear="true"/>
          </a-form-item>

          <a-form-item label="API名称" name="api_name">
            <a-input readonly v-model:value="defForm.data.api_name" placeholder="请输入API名称" :allowClear="true"/>
          </a-form-item>

          <a-form-item label="请求地址" name="path">
            <a-input readonly v-model:value="defForm.data.path" placeholder="请输入请求地址" :allowClear="true"/>
          </a-form-item>

          <a-form-item label="接口状态" name="use_state">
            <a-radio-group v-model:value="defForm.data.use_state">
              <a-radio value="0">启用</a-radio>
              <a-radio value="1">禁用</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="排序" name="sort">
            <a-input-number readonly v-model:value="defForm.data.sort" :min="1" :max="99999"/>
          </a-form-item>

          <a-form-item label="描述信息" name="desc">
            <a-textarea readonly show-count :maxlength="200" v-model:value="defForm.data.desc" placeholder="请输入描述信息"
                        :rows="3"/>
          </a-form-item>
        </div>
        <a-divider style="margin: 0 0 15px 0;padding:0"/>

        <h3>权限与校验</h3>
        <div style="margin-left: 30px">
          <a-form-item label="登录校验" name="check_login">
            <a-radio-group v-model:value="defForm.data.check_login">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="权限校验" name="check_permission">
            <a-radio-group v-model:value="defForm.data.check_permission">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="重复提交校验" name="check_re_submit">
            <a-radio-group v-model:value="defForm.data.check_re_submit">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>
        </div>
        <a-divider style="margin: 0 0 15px 0;padding:0"/>

        <h3>访问限制</h3>
        <div style="margin-left: 30px">

          <a-form-item label="请求方式" name="request_type">
            <a-radio-group v-model:value="defForm.data.request_type">
              <a-radio value="POST">POST</a-radio>
              <a-radio value="GET">GET</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="访问间隔(秒)" name="access_time">
            <a-input-number readonly v-model:value="defForm.data.access_time" :min="0" :max="999999"/>
            <span style="font-size: 12px;color: #CECECE"> * API的访问间隔（0代表无限制）</span>
          </a-form-item>

          <a-form-item label="访问频率(次)" name="access_max_count">
            <a-input-number readonly v-model:value="defForm.data.access_max_count" :min="0" :max="999999"/>
            <span style="font-size: 12px;color: #CECECE"> * 间隔时间内的最大访问次数（默认为1）</span>
          </a-form-item>

          <a-form-item label="总次数限制(次)" name="max_count">
            <a-input-number readonly v-model:value="defForm.data.max_count" :min="0" :max="999999"/>
            <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问总次数（0代表无限制）</span>
          </a-form-item>
        </div>
        <a-divider style="margin: 0 0 15px 0;padding:0"/>

        <h3>操作日志</h3>
        <div style="margin-left: 30px">
          <a-form-item label="保存操作日志" name="log_open_action">
            <a-radio-group v-model:value="defForm.data.log_open_action">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="保存请求参数" name="log_save_request">
            <a-radio-group v-model:value="defForm.data.log_save_request">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="保存响应结果" name="log_save_response">
            <a-radio-group v-model:value="defForm.data.log_save_response">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>
        </div>

      </a-form>

      <!--底部按钮-->
      <template #footer>
        <a-button @click.stop="()=>{option.openInfo = false}">关闭</a-button>
      </template>

    </a-modal>

    <!--底部按钮-->
    <template #footer>
      <a-button @click.stop="closeModal">取消</a-button>
      <a-button type="primary" @click.stop="saveApi">保存</a-button>
    </template>

  </a-modal>
</template>

<script lang="ts">
import {DeleteOutlined, PlusOutlined, SearchOutlined, UndoOutlined} from "@ant-design/icons-vue";
import {requiredBlur, requiredChange} from "@/common/util/validate";
import {useUserStore} from "@/common/store/modules/user";
import {useLayoutStore} from "@/common/store/modules/layout";
import Pagination from "@/common/component/Pagination.vue";
import {saveTableHistory} from "@/common/util/table";
import {copyObj} from "@/common/util/kit";
import { parseTree } from "@/common/util/tree";

export default {
  name: 'SelectApi',
  components: {Pagination, DeleteOutlined, SearchOutlined, UndoOutlined, PlusOutlined},
  mounted() {
    //查询分页
    this.queryPage()
  },
  data() {
    return {
      //store
      userStore: useUserStore(),
      //选项
      option: {
        openAdd: false,
        openEdit: false,
        openInfo: false,
        tableMinHeight: '100%',
        check_login: [
          {label: '开启', value: '0'},
          {label: '关闭', value: '1'},
        ],
        check_permission: [
          {label: '开启', value: '0'},
          {label: '关闭', value: '1'},
        ],
        request_type: [
          {label: 'POST', value: 'POST'},
          {label: 'GET', value: 'GET'},
        ],
        tableSize: [
          {label: '大号', value: 'default'},
          {label: '中号', value: 'middle'},
          {label: '小号', value: 'small'},
        ],
        roleStatus: [
          {label: '启用', value: '0'},
          {label: '停用', value: '1'},
        ],
        checkStatus: [
          {label: '开启', value: '0'},
          {label: '关闭', value: '1'},
        ],
        useStatus: [
          {label: '已启用', value: '0'},
          {label: '已禁用', value: '1'},
        ],
        log_open_action: [
          {label: '开启', value: '0'},
          {label: '关闭', value: '1'},
        ],
        menuTree: [],
        apiTree: [],
      },

      //搜索表单（默认）
      defSearch: {
        param: {
          log_open_action: undefined,
          module_name: undefined,
          api_name: undefined,
          path: undefined,
          use_state: undefined,
        },
        rules: {},
      },
      //表单（默认）
      defForm: {
        //实际表单数据
        data: {},
        initData: {
          request_type: 'POST',
          use_state: '0',
          check_login: '0',
          check_permission: '0',
          check_re_submit: '0',
          access_time: '0',
          access_max_count: '1',
          max_count: '0',
          log_open_action: '1',
          log_save_request: '0',
          log_save_response: '0',
          sort: '100',
        },
        rules: {
          api_name: [requiredBlur],
          module_name: [requiredBlur],
          request_type: [requiredBlur],
          sort: [requiredBlur],
          path: [requiredBlur],
          use_state: [requiredBlur],
          check_login: [requiredBlur],
          check_permission: [requiredBlur],
          check_re_submit: [requiredBlur],
          access_time: [requiredBlur],
          access_max_count: [requiredBlur],
          max_count: [requiredBlur],
          log_open_action: [requiredChange],
          log_save_request: [requiredChange],
          log_save_response: [requiredChange],
        },


      },
      //表格数据（默认）
      defTable: {
        size: 'middle',
        data: [],
        column: [
          {title: 'ID', dataIndex: 'id', ellipsis: true, width: 100, align: 'center', resizable: true},
          {title: '模块名称', dataIndex: 'module_name', ellipsis: true, resizable: true,},
          {title: 'API名称', dataIndex: 'api_name', ellipsis: true, resizable: true},
          {title: '请求地址', dataIndex: 'path', ellipsis: true, resizable: true, align: 'center'},
          {title: '请求方式', dataIndex: 'request_type', resizable: true, align: 'center', width: 80},
          {title: '接口状态', dataIndex: 'use_state', resizable: true, align: 'center'},
          {title: '登录校验', dataIndex: 'check_login', resizable: true, align: 'center'},
          {title: '权限校验', dataIndex: 'check_permission', resizable: true, align: 'center'},
          {title: '保存操作日志', dataIndex: 'log_open_action', resizable: true, align: 'center'},
          // {title: '重复提交校验', dataIndex: 'check_re_submit', resizable: true, align: 'center'},
          {title: '访问间隔(秒)', dataIndex: 'access_time', resizable: true, align: 'center'},
          {title: '访问次数(次)', dataIndex: 'access_max_count', resizable: true, align: 'center'},
          {title: '访问总次数(次)', dataIndex: 'max_count', resizable: true, align: 'center'},
          {title: '排序', dataIndex: 'sort', resizable: true, align: 'center', width: 80},
          {title: '描述信息', dataIndex: 'desc', resizable: true, ellipsis: true},
        ],
        selectKey: [],
        selectRow: [],
        isSaveHistory: true,
        saveHistory: (selectedRowKeys, selectedRows) => {
          let history = saveTableHistory(this.defTable.data, selectedRows, this.defTable.selectRow, "id")
          this.defTable.selectKey = history.keys
          this.defTable.selectRow = history.rows
        },
        rowSelection: () => {
          return {
            type: "checkbox",
            checkStrictly: false,
            selectedRowKeys: this.defTable.selectKey,
            onChange: (selectedRowKeys, selectedRows) => {
              if (this.defTable.isSaveHistory) {
                this.defTable.saveHistory(selectedRowKeys, selectedRows);
              } else {
                this.defTable.selectKey = selectedRowKeys
                this.defTable.selectRow = selectedRows
              }
            },
            onSelect: (record, selected, selectedRows) => {
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
            },
          }
        },
      },
      //分页（默认）
      defPage: {
        current: 1,
        size: 10,
        total: 0,
        type: 'small',
        change: async (current, pageSize) => {
          this.defPage.current = current;
          this.defPage.size = pageSize;
          this.queryPage()
        }
      },
    }
  },
  methods: {
    //查询分页
    queryPage() {
      //加载中
      useLayoutStore().pageLoading = true;
      //参数
      let param = copyObj(this.defSearch.param)
      //分页
      param.size = this.defPage.size
      param.current = this.defPage.current

      this.$http.post('/system/api/list', param).then((res) => {
        //分页
        this.defPage.total = res.total * 1
        //数据
        this.defTable.data = parseTree(res.data)
        useLayoutStore().pageLoading = false;
      })
    },
    //搜索
    search() {
      this.$refs.defSearch.validate().then(() => {
        this.queryPage()
      }).catch(error => {
        this.$message.warning("存在错误，请检查表单填写情况。", 2)
      });

    },
    //重置表单（还原）
    resetForm(formName) {
      let form = this.$refs[formName]
      if (form) {
        form.resetFields()
      }
    },
    //详情
    openInfo(record) {
      this.defForm.data = copyObj(record);
      this.option.openInfo = true;
    },
    closeModal() {
      this.$emit("close", {})
    },
    saveApi() {
      this.$http.post("/system/role/editApi", {ids: this.defTable.selectKey}).then((res) => {
        this.$message.success(res.message,1)
        this.queryPage()
      })

      console.log(this.defTable.selectKey)
      console.log(this.defTable.selectKey.length)
    },
    removeCheck(item) {
      let index1 = this.defTable.selectRow.findIndex(e => e.id == item.id)
      this.defTable.selectRow.splice(index1, 1)

      let index2 = this.defTable.selectKey.indexOf(item.id)
      this.defTable.selectKey.splice(index2, 1)
    },

  }
}
</script>

<style lang="less">
</style>